/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package autodockhelper;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.*;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Paolo
 */
public class ADHFrame extends javax.swing.JFrame {
    public static final File configFile = new File(System.getenv("HOME") + "/.autodockhelper");
    public static File autoGridFile, autoDockFile, workingDir;
    private File gridFile, dockingFile;
    /**
     * Creates new form ADHFrame
     */
    public ADHFrame() {
        gridFile = null;
        dockingFile = null;
        initComponents();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((dim.width - getSize().width) / 2, (dim.height - getSize().height) / 2);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        autoGridPanel = new javax.swing.JPanel();
        autoGridButton = new javax.swing.JButton();
        autoDockPanel = new javax.swing.JPanel();
        autoDockButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openGridMenuItem = new javax.swing.JMenuItem();
        openDockingMenuItem = new javax.swing.JMenuItem();
        separator = new javax.swing.JPopupMenu.Separator();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        autoGridMenuItem = new javax.swing.JMenuItem();
        autoDockMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("AutoDock Helper");
        setIconImage(new ImageIcon (getClass().getResource("/data/icon.png")).getImage());

        autoGridPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("AutoGrid"));

        autoGridButton.setText("Launch AutoGrid");
        autoGridButton.setEnabled(false);
        autoGridButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoGridButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout autoGridPanelLayout = new org.jdesktop.layout.GroupLayout(autoGridPanel);
        autoGridPanel.setLayout(autoGridPanelLayout);
        autoGridPanelLayout.setHorizontalGroup(
            autoGridPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(autoGridPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(autoGridButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 172, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        autoGridPanelLayout.setVerticalGroup(
            autoGridPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(autoGridPanelLayout.createSequentialGroup()
                .add(autoGridButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        autoDockPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("AutoDock"));

        autoDockButton.setText("Launch AutoDock");
        autoDockButton.setEnabled(false);
        autoDockButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoDockButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout autoDockPanelLayout = new org.jdesktop.layout.GroupLayout(autoDockPanel);
        autoDockPanel.setLayout(autoDockPanelLayout);
        autoDockPanelLayout.setHorizontalGroup(
            autoDockPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(autoDockPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(autoDockButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 171, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        autoDockPanelLayout.setVerticalGroup(
            autoDockPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(autoDockPanelLayout.createSequentialGroup()
                .add(autoDockButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        fileMenu.setText("File");

        openGridMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/open.png"))); // NOI18N
        openGridMenuItem.setText("Open grid file...");
        openGridMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openGridMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openGridMenuItem);

        openDockingMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/open.png"))); // NOI18N
        openDockingMenuItem.setText("Open docking file...");
        openDockingMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openDockingMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openDockingMenuItem);
        fileMenu.add(separator);

        exitMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/exit.png"))); // NOI18N
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText("Edit");

        autoGridMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/exe.png"))); // NOI18N
        autoGridMenuItem.setText("AutoGrid location...");
        autoGridMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoGridMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(autoGridMenuItem);

        autoDockMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/exe.png"))); // NOI18N
        autoDockMenuItem.setText("AutoDock location...");
        autoDockMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoDockMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(autoDockMenuItem);

        menuBar.add(editMenu);

        helpMenu.setText("Help");

        aboutMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/data/about.png"))); // NOI18N
        aboutMenuItem.setText("About...");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(autoGridPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(autoDockPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(autoGridPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(autoDockPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void autoGridMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoGridMenuItemActionPerformed
        File file;
        JFileChooser open = new JFileChooser();
        
        open.setDialogTitle("Open");
        open.setDialogType(JFileChooser.OPEN_DIALOG);
        
        if (autoGridFile != null && autoGridFile.isFile()) {
            open.setCurrentDirectory(autoGridFile);
        }
        
        if (open.showOpenDialog(this) == JFileChooser.APPROVE_OPTION &&
                (file = open.getSelectedFile()) != null) {
            updateAutoGridFile(file);
        }
    }//GEN-LAST:event_autoGridMenuItemActionPerformed

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        setVisible(false);
        dispose();
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void autoDockMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoDockMenuItemActionPerformed
        File file;
        JFileChooser open = new JFileChooser();
        
        open.setDialogTitle("Open");
        open.setDialogType(JFileChooser.OPEN_DIALOG);
        
        if (autoDockFile != null && autoDockFile.isFile()) {
            open.setCurrentDirectory(autoDockFile);
        }
        
        if (open.showOpenDialog(this) == JFileChooser.APPROVE_OPTION &&
                (file = open.getSelectedFile()) != null) {
            updateAutoDockFile(file);
        }
    }//GEN-LAST:event_autoDockMenuItemActionPerformed

    private void openGridMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openGridMenuItemActionPerformed
        File file;
        JFileChooser open = new JFileChooser();
        
        open.setDialogTitle("Open");
        open.setDialogType(JFileChooser.OPEN_DIALOG);
        open.setAcceptAllFileFilterUsed(false);
        open.setFileFilter(new FileNameExtensionFilter("AutoGrid file", "gpf", "GPF"));
        
        if (gridFile != null && gridFile.isFile()) {
            open.setCurrentDirectory(gridFile);
            open.setSelectedFile(gridFile);
        }
        else if (workingDir != null && workingDir.isDirectory()) {
            open.setCurrentDirectory(workingDir);
        }
        
        if (open.showOpenDialog(this) == JFileChooser.APPROVE_OPTION &&
                (file = open.getSelectedFile()) != null) {
            
            gridFile = file;
            updateWorkingDir (file);
            
            autoGridButton.setEnabled(true);
        }
    }//GEN-LAST:event_openGridMenuItemActionPerformed

    private void openDockingMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openDockingMenuItemActionPerformed
        File file;
        JFileChooser open = new JFileChooser();
        
        open.setDialogTitle("Open");
        open.setDialogType(JFileChooser.OPEN_DIALOG);
        open.setAcceptAllFileFilterUsed(false);
        open.setFileFilter(new FileNameExtensionFilter("AutoDock file", "dpf", "DPF"));
        
        if (dockingFile != null && dockingFile.isFile()) {
            open.setCurrentDirectory(dockingFile);
            open.setSelectedFile(dockingFile);
        }
        else if (workingDir != null && workingDir.isDirectory()) {
            open.setCurrentDirectory(workingDir);
        }
        
        if (open.showOpenDialog(this) == JFileChooser.APPROVE_OPTION &&
                (file = open.getSelectedFile()) != null) {
            
            dockingFile = file;
            updateWorkingDir (file);
            
            autoDockButton.setEnabled(true);
        }
    }//GEN-LAST:event_openDockingMenuItemActionPerformed

    private void autoGridButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoGridButtonActionPerformed
        if (autoGridFile != null && autoGridFile.isFile()) {
            
            autoGridButton.setEnabled(false);
            autoGridButton.setText("");
            autoGridButton.setIcon(new ImageIcon(getClass().getResource("/data/loading.gif")));
            autoGridMenuItem.setEnabled(false);
            openGridMenuItem.setEnabled(false);
            
            new AutoGridThread(this, gridFile).start();
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose AutoGrid executable first!", "WARNING!", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_autoGridButtonActionPerformed

    private void autoDockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoDockButtonActionPerformed
        if (autoDockFile != null && autoDockFile.isFile()) {
            
            autoDockButton.setEnabled(false);
            autoDockButton.setText("");
            autoDockButton.setIcon(new ImageIcon(getClass().getResource("/data/loading.gif")));
            autoDockMenuItem.setEnabled(false);
            openDockingMenuItem.setEnabled(false);
            
            new AutoDockThread(this, dockingFile).start();
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose AutoDock executable first!", "WARNING!", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_autoDockButtonActionPerformed

    private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
        String message = "\n   AutoDock Helper\n" +
                         "       Version 1.0\n\n" + 
                         "© 2012 - Paolo Gatti\n" +
                         "n3o.eden@gmail.com";
        JOptionPane.showMessageDialog(this, message, "About...", JOptionPane.PLAIN_MESSAGE,
                new ImageIcon(getClass().getResource("/data/aboutImg.png")));
    }//GEN-LAST:event_aboutMenuItemActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        if (configFile.isFile()) {
            
            try {
                String line, key, value;
                String content = "";
                BufferedReader in = new BufferedReader (new FileReader (configFile));
                
                while ((line = in.readLine()) != null) {
                    content += line + "\n";
                }
                in.close();
                
                StringTokenizer t = new StringTokenizer(content, "\n"), t2;
                
                while (t.hasMoreTokens()) {
                    line = t.nextToken();
                    t2 = new StringTokenizer (line, "=");
                    key = t2.nextToken().trim();
                    value = t2.nextToken().trim();
                    if (key.equals("AutoGrid")) {
                        autoGridFile = new File (value);
                    }
                    else if (key.equals("AutoDock")) {
                        autoDockFile = new File (value);
                    }
                    else if (key.equals("WorkingDir")) {
                        workingDir = new File (value);
                    }
                    else {
                        throw new IOException();
                    }
                }
                in.close();
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
        
        Locale.setDefault(Locale.US);
        
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ADHFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ADHFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ADHFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ADHFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ADHFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    javax.swing.JButton autoDockButton;
    javax.swing.JMenuItem autoDockMenuItem;
    private javax.swing.JPanel autoDockPanel;
    javax.swing.JButton autoGridButton;
    javax.swing.JMenuItem autoGridMenuItem;
    private javax.swing.JPanel autoGridPanel;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenuBar menuBar;
    javax.swing.JMenuItem openDockingMenuItem;
    javax.swing.JMenuItem openGridMenuItem;
    private javax.swing.JPopupMenu.Separator separator;
    // End of variables declaration//GEN-END:variables
    
    private static void updateAutoGridFile(File file) {
        autoGridFile = file;
        
        boolean keyFound = false;
        try {
            if (configFile.isFile()) {
                String line, line2, key, value;
                String content = "";
                BufferedReader in = new BufferedReader (new FileReader (configFile));

                while ((line = in.readLine()) != null) {
                    content += line + "\n";
                }
                in.close();

                PrintWriter out = new PrintWriter (new FileWriter (configFile));
                StringTokenizer t = new StringTokenizer(content, "\n"), t2;

                while (t.hasMoreTokens()) {
                    line2 = t.nextToken();
                    t2 = new StringTokenizer (line2, "=");
                    key = t2.nextToken().trim();
                    value = t2.nextToken().trim();
                    if (! key.equals("AutoGrid")) {
                        out.println(line2);
                    }
                    else {
                        keyFound = true;
                        out.println("AutoGrid = " + autoGridFile.getPath());
                    }
                }
                if (! keyFound) {
                    out.println("AutoGrid = " + autoGridFile.getPath());
                }
                out.close();
            }
            else {
                PrintWriter out = new PrintWriter (new FileWriter (System.getenv("HOME") + "/.autodockhelper"));
                out.println("AutoGrid = " + autoGridFile.getPath());
                out.close();
            }

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    private static void updateAutoDockFile(File file) {
        autoDockFile = file;
        
        boolean keyFound = false;
        try {
            if (configFile.isFile()) {
                String line, line2, key, value;
                String content = "";
                BufferedReader in = new BufferedReader (new FileReader (configFile));

                while ((line = in.readLine()) != null) {
                    content += line + "\n";
                }
                in.close();

                PrintWriter out = new PrintWriter (new FileWriter (configFile));
                StringTokenizer t = new StringTokenizer(content, "\n"), t2;

                while (t.hasMoreTokens()) {
                    line2 = t.nextToken();
                    t2 = new StringTokenizer (line2, "=");
                    key = t2.nextToken().trim();
                    value = t2.nextToken().trim();
                    if (! key.equals("AutoDock")) {
                        out.println(line2);
                    }
                    else {
                        keyFound = true;
                        out.println("AutoDock = " + autoDockFile.getPath());
                    }
                }
                if (! keyFound) {
                    out.println("AutoDock = " + autoDockFile.getPath());
                }
                out.close();
            }
            else {
                PrintWriter out = new PrintWriter (new FileWriter (System.getenv("HOME") + "/.autodockhelper"));
                out.println("AutoDock = " + autoDockFile.getPath());
                out.close();
            }

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    private static void updateWorkingDir(File file) {
        workingDir = file.getParentFile();
        
        boolean keyFound = false;
        try {
            if (configFile.isFile()) {
                String line, line2, key, value;
                String content = "";
                BufferedReader in = new BufferedReader (new FileReader (configFile));

                while ((line = in.readLine()) != null) {
                    content += line + "\n";
                }
                in.close();

                PrintWriter out = new PrintWriter (new FileWriter (configFile));
                StringTokenizer t = new StringTokenizer(content, "\n"), t2;
                
                while (t.hasMoreTokens()) {
                    line2 = t.nextToken();
                    t2 = new StringTokenizer (line2, "=");
                    key = t2.nextToken().trim();
                    value = t2.nextToken().trim();
                    if (! key.equals("WorkingDir")) {
                        out.println(line2);
                    }
                    else {
                        keyFound = true;
                        out.println ("WorkingDir = " + workingDir.getPath());
                    }
                }
                if (! keyFound) {
                    out.println ("WorkingDir = " + workingDir.getPath());
                }
                out.close();
            }
            else {
                PrintWriter out = new PrintWriter (new FileWriter (System.getenv("HOME") + "/.autodockhelper"));
                out.println("WorkingDir = " + workingDir.getPath());
                out.close();
            }

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
